<template>
  <view>
    <!-- parse <template is="skeleton" v-if="loading"/> -->


    <view class="body">
      <view class="banner-container">
		<image v-if="coupon.couponBannerUrl" class="banner" :src="baseImgUrl + coupon.couponBannerUrl">
        <image v-if="!coupon.couponBannerUrl" class="banner" :src="staticBaseUrl + '/static/image/coupon-banner.png'"></image>
        <view v-if="!coupon.couponBannerUrl" class="banner-content">
          <!-- <text class="merchant-name">{{coupon.couponName}}</text> -->
          <view class="coupon-info">
            <text
              v-if="coupon.couponType == 1 || coupon.couponType == 3 || coupon.couponType == 5 || coupon.couponType == 6"
              class="coupon-amount">
              抵扣 ￥
              <text style="font-size: 70rpx">{{ formatFenMoney(coupon.discountAmt) }}</text>
              元
            </text>
            <text v-else-if="coupon.couponType == 2 || coupon.couponType == 4" class="coupon-amount">
              尊享
              <text style="font-size: 70rpx">{{ coupon.discountAmt }}</text>
              折
            </text>
            <text v-if="coupon.couponType == 7" style="font-size: 30rpx; width: 370rpx">{{ coupon.couponName }}</text>
          </view>
        </view>
      </view>

      <view class="coupon-detail">
        <view class="merchant-name">{{ coupon.couponName }}</view>

        <view class="detail-content">
          <view class="detail-title">
            <text class="cycle"></text>
            <text>使用条件</text>
          </view>
          <view class="detail-info">
            <block v-if="coupon.couponType == 1 || coupon.couponType == 3 || coupon.couponType == 5">
              <text>满{{ formatFenMoney(coupon.useCondAmt) }}元减{{ formatFenMoney(coupon.discountAmt) }}元</text>
            </block>
            <block v-else-if="coupon.couponType == 2 || coupon.couponType == 4">
              <text>满{{ formatFenMoney(coupon.useCondAmt) }}元尊享{{ coupon.discountAmt }}折,最高减{{ formatFenMoney(coupon.maxPromotionAmt) }}元</text>
            </block>
            <block v-else>
              <text>无</text>
            </block>
          </view>
        </view>

        <view class="detail-content">
          <view class="detail-title">
            <text class="cycle"></text>
            <text>有效期限</text>
          </view>
          <block v-if="coupon.expireDateType == 1">
            <view class="detail-info">{{ coupon.expireBeginTime }} ~ {{ coupon.expireEndTime }}</view>
          </block>
          <block v-else-if="coupon.expireDateType == 2">
            <view class="detail-info">
              <text>优惠券领取后{{ coupon.expireDaysNum }}天内可用</text>
            </view>
          </block>
        </view>

        <view class="detail-content">
          <view class="detail-title">
            <text class="cycle"></text>
            <text>使用说明</text>
          </view>
          <view class="detail-info">
            <text>{{ coupon.description }}</text>
          </view>
        </view>

        <!-- <view wx:if="{{!util.isEmpty(coupon.price) && coupon.price>0}}" class="pay-container">
			<text class="pay-title">购买金额</text>
			<text class="pay-amount">￥{{formatFenMoney(coupon.price)}}</text>
		</view> -->
      </view>

      <coupon-mcht-list :coupon-id="couponId"></coupon-mcht-list>

      <view class="pay-container">
        <view class="pay-left">
          <text>
            <text v-if="coupon.exchangePrice" class="item-exchange">
              <text style="font-size: 24rpx">￥</text>
              {{ coupon.exchangePrice }}
            </text>
            <text v-if="coupon.exchangePrice && coupon.exchangePoint">+</text>
            <text v-if="coupon.exchangePoint" class="item-exchange">
              {{ coupon.exchangePoint }}
              <text class="pay-left">积分</text>
            </text>
          </text>
        </view>
        <block v-if="coupon.totalNum - coupon.getNum > 0">
          <view v-if="coupon.isFree" class="btn btn-free" :style="'background-color:' + platformConfig.baseColor"
            @tap.stop.prevent="sumbitOrder" :disabled="!btnEnable">
            免费领取
          </view>
          <button v-else class="btn" :style="'background:' + platformConfig.baseColor" @tap.stop.prevent="showConfirmFun()"
            :disabled="!btnEnable">立即购买</button>
        </block>
        <block v-else>
          <button class="btn" disabled>券已售罄</button>
        </block>
      </view>

      <u-popup :show="showConfirm" @close="onClose">
        <view class="pop-confirm-container">
          <view class="confirm-title">确认</view>
          <view class="confirm-info">
            <text>您是否确认花费</text>
            <text>
              <text v-if="coupon.exchangePrice">
                <text>￥</text>
                {{ coupon.exchangePrice }}
              </text>
              <text v-if="coupon.exchangePrice && coupon.exchangePoint">+</text>
              <text v-if="coupon.exchangePoint">
                {{ coupon.exchangePoint }}
                <text>积分</text>
              </text>
            </text>
            <text>兑换优惠券?</text>
          </view>
          <view class="confirm-btn">
            <view class="confirm-btn-cancel" @tap="onClose">取消</view>
            <view class="confirm-btn-ok"
              :style="'background: linear-gradient(140deg, ' + platformConfig.gradientColors[0] + ' 0%, ' + platformConfig.gradientColors[1] + ' 100%);'"
              @tap="sumbitOrder">
              确认
            </view>
          </view>
        </view>
      </u-popup>

      <view class="viewMission">
        <block v-if="viewMission">
          <image src="/static/image/view-unfinished@2x.png" style="width: 100rpx; height: 140rpx"></image>
          <text class="endTimer">浏览{{ timeCount }}秒可得奖励</text>
        </block>
        <image class="viewMission-complete" v-if="hasComplete" src="/static/image/view-complete2@2x.png"
          @tap="receivePrice"></image>
      </view>
    </view>
  </view>
</template>
<!-- <script module="util" lang="wxs" src="../../../utils/util.wxs"></script> -->
<script>
  import {
    http
  } from '@/utils/commonRequest.js'; // 局部引入
  import couponMchtList from '@/components/couponMchtList/couponMchtList';
  // import vanPopup from '@vant/weapp/popup/index';
  const app = getApp();

  const utils = require('./../../../utils/util.js');
	import {
		staticBaseUrl, baseImgUrl
	} from '@/utils/constant.js'
	
  export default {
    components: {
      couponMchtList,
      // vanPopup
    },
    data() {
      return {
		staticBaseUrl: staticBaseUrl,
		baseImgUrl,
        platformConfig: app.globalData.platformConfig,
        loading: true,
        couponId: null,
        mchntId: null,
        coupon: {},
        memberInfo: null,
        btnEnable: true,
        mersList: [],
        allMerchant: true,
        showConfirm: false,
        viewMission: false,
        hasComplete: false,
        dicType: '',
        dictId: '',
        taskId: '',
        timeCount: '10',
        timeOut: '',
        share: null,
        managerId: null,
        saleRuleId: ''
      };
    },
    onLoad: function(options) {
      this.platformConfig = app.globalData.platformConfig
      let that = this;

      if (!utils.isEmpty(options) && !utils.isEmpty(options.couponId)) {
        that.couponId = options.couponId
        that.saleRuleId = options.saleRuleId
        that.managerId = utils.isEmpty(options.managerId) ? '' : options.managerId
        this.$checkLogin()
          .then((res) => {
            console.log('$checkLogin')
            that.queryCouponDetail(options.couponId, options.saleRuleId);
          })
          .catch((err) => {
            console.log(err);
          });

        if (options.dictId) {
          that.viewMission = options.share ? false : true
          that.dicType = options.dicType
          that.dictId = options.dictId
          that.taskId = options.taskId
          that.share = options.share
        }
      } else if (!utils.isEmpty(options) && !utils.isEmpty(options.scene)) {
        let scene = options.scene;
        this.$checkLogin()
          .then((res) => {
            http.get('miniapp/getQrCodeParam', {
                params: {
                  scene: scene
                }
              })
              .then((res) => {
                if (200 == res.data.code) {
                  let params = JSON.parse(res.data.miniappPromoCode.pageParam);
                  that.couponId = params.couponId
                  that.saleRuleId = params.saleRuleId
                  that.managerId = params.managerId
                  that.queryCouponDetail(params.couponId, params.saleRuleId);
                } else {
                  return utils.tips('参数异常');
                }
              });
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        that.loading = false
        return utils.tips('参数异常');
      }
    },
    onShow: function() {
      if (null == this.memberInfo && null != app.globalData.memberInfo) {
        let memberInfo = app.globalData.memberInfo;
        this.memberInfo = memberInfo
      }

      if (this.dictId && !this.share) {
        this.timeOutStart();
      }
    },
    /** 页面隐藏 */
    onHide: function() {
      clearTimeout(this.timeOut);
    },
    /** 页面关闭 */
    onUnload: function() {
      clearTimeout(this.timeOut);
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function(options) {
      let that = this;

      if (that.share == undefined) {
        return;
      } else {
        that.taskAddLog();
        return {
          title: '分享测试',
          path: '/pages/coupon/couponDetail/couponDetail?couponId=' + that.couponId + '&saleRuleId=' + that.saleRuleId
        };
      }
    },
    /** 分享 */
    onShareTimeline: function() {
      let that = this;
      console.log(that.dicType, that.dictId);

      if (that.share == undefined) {
        return;
      } else {
        that.taskAddLog();
        return {
          title: '分享测试',
          path: '/pages/coupon/couponDetail/couponDetail?couponId=' + that.couponId + '&saleRuleId=' + that.saleRuleId
        };
      }
    },
    methods: {
      formatFenMoney(s) {
        if (undefined == s || '' == s || null == s) {
          return 0;
        } else {
          return (s / 100)
        }
      },
      //获取优惠券详情
      queryCouponDetail: function(couponId, saleRuleId) {
        let that = this;

        if (utils.isEmpty(couponId)) {
          return;
        } else {
          let params = {
            couponId: couponId,
            saleRuleId: saleRuleId == 'undefined' ? '' : saleRuleId
          };
          http.get('/zsnshCoupon/getCouponDetail', {
            params: params
          }).then((res) => {
            if (200 == res.data.code) {
              console.log(res);
              that.coupon = res.data.couponInfo
              that.allMerchant = res.data.allMerchant
              that.mersList = res.data.mersList
            } else {
              utils.tips('未查询到优惠券信息');
            }
            that.loading = false
          });
        }
      },

      //下单支付
      sumbitOrder: function() {
        utils.showLoading('请稍候...');
        this.btnEnable = !this.btnEnable
        let that = this;
        let price = that.coupon.exchangePrice;
        console.log(price);
        let couponId = that.couponId;
        let coupon = that.coupon;
        console.log(coupon);

        if (utils.isEmpty(couponId)) {
          utils.tips('未获取到优惠券信息');
          utils.hideLoading();
          return;
        }

        this.$checkAuth()
          .then((result) => {
            let saleRuleId = coupon.exchangeId == undefined ? '' : coupon.exchangeId;
            let params = {
              couponId: coupon.couponId,
              saleRuleId: saleRuleId,
              mgrId: this.managerId
            };
						// #ifdef MP-WEIXIN
						params.paySource = 'miniApp'
						// #endif
            console.log('执行第一步')
            http.get('/zsnshCoupon/couponOrderCommit', {
                params: params
              })
              .then((res) => {
                console.log('执行第二步')
                if (200 == res.data.code) {
                  console.log(res);
                  let needPay = res.data.needPay;

                  if (coupon.isFree) {
                    utils.tips('优惠券领取中，请以实际领取情况为准！');
                    console.log(res);
                    setTimeout(function() {
                      if (coupon.couponOrigin == '1') {
                        uni.redirectTo({
                          url: '/pages/coupon/myCoupon/myCoupon'
                        });
                      }

                      uni.redirectTo({
                        url: '/pages/coupon/myCoupon/myCoupon?couponCodeStatus=1'
                      });
                    }, 1500);
                  } else {
                    let payId = res.data.payId;
                    that.payId = payId;

                    if (needPay) {
                      utils.hideLoading();
                      app.globalData.toCouponPay(payId, price);
                    } else {
                      if (res.data.code == 500) {
                        utils.hideLoading();
                        utils.message(res.data.msg);
                      } else {
                        utils.hideLoading();
                        uni.navigateTo({
                          url: '/pages/payResult/payResult?payId=' + that.payId
                        });
                      }
                    }

                    utils.hideLoading();
                  }
                } else if (500 == res.data.code) {
                  utils.message(res.data.msg);
                  console.log('优惠券领取失败：', res.data.msg);
                  utils.hideLoading();
                } else {
                  utils.message('优惠券领取失败，请稍后再试');
                  console.log('优惠券领取失败：', res.data.msg);
                  utils.hideLoading();
                }

                that.onClose();
              })
              .catch((err) => {
                utils.hideLoading();
                that.onClose();
              });
          })
          .catch((err) => {
            utils.hideLoading();
            console.log(err);
          });
      },

      /**
       * 查询订单支付状态
       * @param {*} payId
       */
      queryResult: function(payId) {
        let that = this;
        setTimeout(() => {
          that.queryResultLoop(payId, 0);
        }, 2000);
      },

      /**
       * 循环查询支付结果，最多查询三次
       * @param {*} payId
       * @param {*} time
       */
      queryResultLoop: function(netpayOrderId, time) {
        let that = this;

        if (time >= 3) {
          uni.hideLoading();
          utils.message('优惠券领取中，请以实际领取情况为准！', () => {
            uni.navigateTo({
              url: '/pages/coupon/myCouponList/myCouponList'
            });
          });
        } else {
          http.get('/zsnshCoupon/payResult', {
              params: {
                netpayOrderId: netpayOrderId
              }
            })
            .then((res) => {
              if (200 == res.data.code) {
                uni.hideLoading();
                uni.showToast({
                  title: '支付成功',
                  duration: 3000
                });
                that.btnEnable = !that.btnEnable
                setTimeout(() => {
                  uni.navigateTo({
                    url: '/pages/payResult/payResult?payId=' + that.payId
                  });
                }, 2000);
              } else {
                setTimeout(() => {
                  that.queryResultLoop(payId, ++time);
                }, 3000);
              }
            });
        }
      },

      showConfirmFun: function() {
        let that = this;
        that.showConfirm = true
      },

      onClose: function() {
        let that = this;
        that.showConfirm = false
      },

      getTips: function(tipsCode) {
        if (undefined == tipsCode || null == tipsCode || '' == tipsCode || ' ' == tipsCode) {
          return null;
        }

        var tips = {
          NOT_EXIST_SESSION: '登录超时，请重新登录',
          NOT_EXIST_MOBILE: '请求参数异常',
          NOT_EXIST_COUPON: '您领取的优惠券已下架',
          NOT_HAVE_MERCHANT: '优惠券对应商户不存在',
          EXIST_NOT_PAY_ORDER: '您还有尚未支付的优惠券订单，请前往支付',
          NOT_ACCESS_RULE_CHECK: '未查找到优惠券领取或放券规则',
          NO_MORE_COUPON: '优惠券已售罄'
        };
        return undefined != tips[tipsCode] ? tips[tipsCode] : '优惠券下单失败';
      },

      /** 完成任务返回 */
      receivePrice: function() {
        uni.navigateBack({
          delta: 1
        });
      },

      timeOutStart: function() {
        let that = this;
        let type = that.dicType;
        let id = that.dictId;
        let taskId = that.taskId;
        that.timeOut = setInterval(function() {
          let count = that.timeCount - 1;
          that.timeCount = count

          if (that.timeCount == 0) {
            that.viewMission = false
            that.hasComplete = true
            app.globalData.taskLog(type, id, taskId);
            clearInterval(that.timeOut);
          }
        }, 1000);
      },

      taskAddLog: function() {
        let that = this;
        let type = that.dicType;
        let id = that.dictId;
        let taskId = that.taskId;
        app.globalData.taskLog(type, id, taskId, 'share');
      }
    }
  };
</script>
<style>
  /* @import './couponDetail.skeleton.css'; */

  .body {
    padding-bottom: 120rpx;
    font-size: 26rpx;
    background-color: #f6f9ff;
  }

  .banner-container {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .banner {
    width: 688rpx;
    height: 210rpx;
  }

  .banner-content {
    position: absolute;
    top: 0;
    left: 80rpx;
    height: 210rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 50rpx 0;
    color: #fff;
  }

  .coupon-info {
    display: flex;
    align-items: flex-end;
    line-height: 1;
  }

  .coupon-amount {
    margin-right: 30rpx;
    margin-top: 40rpx;
    font-size: 40rpx;
    font-weight: bold;
  }

  .coupon-detail,
  .store-container {
    margin: 36rpx;
    padding: 40rpx;
    box-shadow: 10rpx 10rpx 10rpx 10rpx #fafafa, -10rpx -10rpx 10rpx 10rpx #fafafa;
    background-color: #fff;
    border-radius: 16rpx;
  }

  .detail-content {
    color: #666;
    margin-top: 32rpx;
    line-height: 50rpx;
    font-size: 24rpx;
  }

  .merchant-name {
    font-size: 30rpx;
    color: #333;
    font-weight: 600;
    border-bottom: 1px solid #f4f5f7;
    padding-bottom: 18rpx !important;
  }

  .detail-title {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    font-weight: bold;
    color: #444;
  }

  .cycle {
    margin-right: 12rpx;
    width: 4rpx;
    height: 24rpx;
    background: #ed171f;
    height: 24rpx;
  }

  .detail-info {
    padding-left: 32rpx;
  }

  .store-container {}

  .store-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    border-bottom: 1px solid #f4f5f7;
  }

  .store-header-text {
    font-size: 30rpx;
    color: #333;
    font-weight: bold;
  }

  .store-header-nav {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #999;
  }

  .icon-arrow {
    margin-left: 16rpx;
    width: 24rpx;
    height: 24rpx;
  }

  .store-list {
    padding: 10rpx 0;
  }

  .store-item {
    margin-top: 20rpx;
    color: #444;
    font-size: 28rpx;
  }

  .pay-container {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 120rpx;
    padding: 0 32rpx;
    background: #ffffff;
    box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.5);
    /* margin: 50rpx 0 10rpx; */
  }

  .pay-left {
    color: #444;
    font-weight: bold;
    font-size: 34rpx;
    letter-spacing: -1px;
  }

  .item-exchange {
    color: #ff5642;
    font-size: 40rpx;
  }

  .pay-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
  }

  .pay-amount {
    font-size: 32rpx;
    font-weight: bold;
    color: #c02424;
  }

  .btn {
    padding: 0;
    font-size: 34rpx;
    font-weight: bold;
    color: #fff;
    width: 208rpx !important;
    line-height: 84rpx;
    text-align: center;
    background: #ff5642;
    border-radius: 42px;
    margin: 0 !important;
  }

  .btn[disabled] {
    /* background-color: rgba(255, 86, 66, 0.52) !important; */
		opacity: 0.8;
    color: #fff !important;
  }

  .btn-free {
    width: 90% !important;
    position: absolute;
    top: 20%;
    left: 50%;
    transform: translate(-50%);
    letter-spacing: 2rpx;
  }

  .van-popup {
    border-radius: 18rpx !important;
  }

  .pop-confirm-container {
    width: 690rpx;
    height: 450rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 60rpx;
  }

  .confirm-title {
    font-size: 36rpx;
    font-weight: 600;
    margin-bottom: 60rpx;
  }

  .confirm-info {
    font-size: 28rpx;
    font-weight: 600;
    margin-bottom: 80rpx;
  }

  .confirm-btn {
    width: 100%;
    display: flex;
    border-top: 1px solid #eaeaea;
    padding: 40rpx 60rpx 0;
    justify-content: space-between;
  }

  .confirm-btn-cancel {
    width: 260rpx;
    height: 80rpx;
    border-radius: 40rpx;
    border: 1px solid #eaeaea;
    text-align: center;
    line-height: 80rpx;
    color: #666;
    font-size: 34rpx;
    font-weight: 500;
  }

  .confirm-btn-ok {
    width: 260rpx;
    height: 80rpx;
    border-radius: 40rpx;
    text-align: center;
    line-height: 80rpx;
    color: #fff;
    background: linear-gradient(140deg, #ffc996 0%, #ed176e 100%);
    font-size: 34rpx;
    font-weight: 500;
  }

  .viewMission {
    position: fixed;
    right: 24rpx;
    top: 50%;
    transform: translateY(-50%);
    z-index: 999;
    /* zoom: .6; */
  }

  .viewMission-complete {
    width: 100rpx;
    height: 140rpx;
    /* zoom: 0.6; */
  }

  .endTimer {
    display: inline-block;
    width: 54rpx;
    height: 56rpx;
    /* line-height: 20rpx; */
    font-size: 12rpx;
    font-weight: 500;
    color: #fff;
    position: absolute;
    top: 70rpx;
    left: 24rpx;
    text-align: center;
    padding-top: 4rpx;
  }
</style>
